package com.wsp.service.service;

import com.wsp.apimanagement.pojo.dto.Result;
import com.wsp.apimanagement.pojo.entity.Admin;
import com.wsp.apimanagement.pojo.entity.Module;
import com.wsp.apimanagement.pojo.entity.Source;
import com.wsp.apimanagement.service.ModuleService;
import com.wsp.apimanagement.util.CommonResultBuilderUtil;
import com.wsp.service.util.EncryptionUtil;
import com.wsp.service.util.QiNiuCdnUtil;
import com.wsp.service.mapper.AdministratorMapper;
import com.wsp.apimanagement.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.BufferedInputStream;

/**
 * Package: com.wsp.apimanagement.service
 * Description： TODO
 *
 * @Author: 巫思平
 * Copyright: Copyright (c) 2020
 * Version: 1
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdministratorMapper adminMapper;
    @Autowired
    private QiNiuCdnUtil cdnUtil;
    @Autowired
    private ModuleService moduleService;

    @Override
    public Result<Module> insertModule(String name, BufferedInputStream file, String fileName) {
        String moduleCover = cdnUtil.uploadCommonFile(fileName,file);
        Module module = new Module();
        module.setModuleName(name);
        module.setModuleCover(moduleCover);
        adminMapper.insertModule(module);
        return Result.<Module>builder().code(200).msg("SUCCESS").data(module).build();
    }

    @Override
    public Result<Source> insertSource(String moduleName, String sourceTitle, BufferedInputStream file, String fileName) {
        Module module = moduleService.findModuleByName(moduleName);
        if(module == null){
            return CommonResultBuilderUtil.commonError("无效资源");
        }
        Source source = new Source();
        source.setModuleId(module.getModuleId());
        source.setSourceTitle(sourceTitle);
        source.setSourcePath(cdnUtil.uploadBigCommonFile(fileName,file));
        adminMapper.insertSource(source);
        return Result.<Source>builder().code(200).msg("SUCCESS").data(source).build();
    }

    @Override
    public Result<Source> insertCover(long sourceId, BufferedInputStream file, String fileName) {
        String sourceCover = cdnUtil.uploadCommonFile(fileName,file);
        adminMapper.updateCover(sourceId,sourceCover);
        return Result.<Source>builder().code(200).msg("SUCCESS").data(null).build();
    }

    @Override
    public void insertAdmin(Admin admin) {
        admin.setPassword(EncryptionUtil.encoding(admin.getPassword()));
        adminMapper.insertAdmin(admin);
    }

    @Override
    public Admin queryAdminByCount(String adminCount) {
        return adminMapper.queryAdminByCount(adminCount);
    }
}
